import { Message } from 'element-ui'
import { Notification } from 'element-ui'
import {JSEncrypt} from 'jsencrypt'

// import CronExpressionValidator from './CronExpressionValidator';

import C from './cfg'

let SIGN_REGEXP = /([yMdhsm])(\1*)/g
let DEFAULT_PATTERN = 'yyyy-MM-dd'
function padding (s, len) {
  len = len - (s + '').length
  for (let i = 0; i < len; i++) {
    s = '0' + s
  }
  return s
}

class fun {
  constructor () {
  }

  getQueryStringByName (name) {
    let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
    let r = window.location.search.substr(1).match(reg)
    let context = ''
    if (r != null)
      context = r[2]
    reg = null
    r = null
    return context == null || context == '' || context == 'undefined' ? '' : context
  }

  formatDate () {
    let a = {
      format: function (date, pattern) {
        pattern = pattern || DEFAULT_PATTERN
        return pattern.replace(SIGN_REGEXP, function ($0) {
          switch ($0.charAt(0)) {
            case 'y':
              return padding(date.getFullYear(), $0.length)
            case 'M':
              return padding(date.getMonth() + 1, $0.length)
            case 'd':
              return padding(date.getDate(), $0.length)
            case 'w':
              return date.getDay() + 1
            case 'h':
              return padding(date.getHours(), $0.length)
            case 'm':
              return padding(date.getMinutes(), $0.length)
            case 's':
              return padding(date.getSeconds(), $0.length)
          }
        })
      },
      parse: function (dateString, pattern) {
        let matchs1 = pattern.match(SIGN_REGEXP)
        let matchs2 = dateString.match(/(\d)+/g)
        if (matchs1.length == matchs2.length) {
          let _date = new Date(1970, 0, 1)
          for (let i = 0; i < matchs1.length; i++) {
            let _int = parseInt(matchs2[i])
            let sign = matchs1[i]
            switch (sign.charAt(0)) {
              case 'y':
                _date.setFullYear(_int)
                break
              case 'M':
                _date.setMonth(_int - 1)
                break
              case 'd':
                _date.setDate(_int)
                break
              case 'h':
                _date.setHours(_int)
                break
              case 'm':
                _date.setMinutes(_int)
                break
              case 's':
                _date.setSeconds(_int)
                break
            }
          }
          return _date
        }
        return null
      }
    }
  }

  getCookie (c_name) {

    let c_start, c_end
    if (document.cookie.length > 0) {
      c_start = document.cookie.indexOf(c_name + '=')
      if (c_start != -1) {
        c_start = c_start + c_name.length + 1
        c_end = document.cookie.indexOf(';', c_start)
        if (c_end == -1) c_end = document.cookie.length
        return unescape(document.cookie.substring(c_start, c_end))
      }
    }
    return ''
  }

  setCookie (c_name, value, expiredays) {
    let exdate = new Date()
    exdate.setDate(exdate.getDate() + expiredays)
    document.cookie = c_name + '=' + escape(value) + ((expiredays == null) ? '' : '; expires=' + exdate.toGMTString())
  }

  /**
   * 时间戳转化为时间
   * @param number
   * @returns Date
   */
  pokeToTime (poke) {
    let time = parseInt(poke) || 0
    if (time < 1000000000000) {
      time = time * 1000
    }
    let newDate = new Date()
    let rtime
    newDate.setTime(time)
    function toTenNum (e) {
      let num = e || {}
      return (e < 10) ? e = '0' + e : e = e
    }

    rtime = newDate.getFullYear() + '/' + toTenNum(newDate.getMonth() + 1) + '/' + toTenNum(newDate.getDate()) + ' ' + toTenNum(newDate.getHours()) + ':' + toTenNum(newDate.getMinutes())
    return rtime
  }

  /**
   * 回调提示
   * @param number
   * @returns
   */
  callbackTips (val) {

    let retCode = 0;
    (typeof (val) == 'string') ? retCode = parseInt(val) : retCode = parseInt(val.retCode)
    let initTips = retCode + '操作失败'
    let initType = 'error'
    Message({
      type: C.RESPONSE_WORK_BOOK[retCode].type || initType,
      message: C.RESPONSE_WORK_BOOK[retCode].tips || initTips
    })

  }

  apiMsg (res) {
    if (res.body && res.body.retCode != undefined) {
      /*  Message({
       type: 'warning',
       message: `${res.body.retCode} : ${res.body.retMsg}`,
       })*/
    }
  }

  page_sart_index (body) {
    body || (body = {})
    if (body.start_index && body.page_count) {
      body.start_index = (body.start_index - 1) * body.page_count + 1
    }
    return body
  }

  requset_before (body) {
    this.page_sart_index(body)
  }

  resInit (res) {
    res.FX = {}
    this.resIsOk(res)
  }

  resIsOk (res) {
    res.FX || (res.FX = {})
    res.FX.ok = true
    res.FX.err = false
    if (!res.body || res.body.retCode != 200) {
      res.FX.ok = false
      res.FX.err = true
    }
  }

  getPathJson (hdfs_dir, type) {
    return {
      file_id: '',
      file_name: '',
      hdfs_file_path: hdfs_dir || '',
      // file_type: type
    }
  }

  hdfsPath2Jsom (hdfs_dir, type) {
    if (hdfs_dir == '' || !hdfs_dir || hdfs_dir == []) return []
    if (hdfs_dir.length == 0)return []
    return [this.getPathJson(hdfs_dir, type)]
  }

  compareTime (date1, date2) {
    let date3 = date2.getTime() - date1.getTime()  //时间差的毫秒数

    //计算出相差天数
    let days = Math.floor(date3 / (24 * 3600 * 1000))

    //计算出小时数

    let leave1 = date3 % (24 * 3600 * 1000)    //计算天数后剩余的毫秒数
    let hours = Math.floor(leave1 / (3600 * 1000))
    //计算相差分钟数
    let leave2 = leave1 % (3600 * 1000)       //计算小时数后剩余的毫秒数
    let minutes = Math.floor(leave2 / (60 * 1000))

    //计算相差秒数
    let leave3 = leave2 % (60 * 1000)    //计算分钟数后剩余的毫秒数
    let seconds = Math.round(leave3 / 1000)
    return `${days}天${hours}小时${minutes}分钟${seconds}秒`
  }

  pwStrength (val) {
    (typeof  val != 'string' ) ? val = '' : void 0
    let lvTxts = ['', '低', '中', '高']
    let lvClass = ['#FF4949', '#FF4949', '#F7BA2A', '#13CE66']
    let lv = 0
    if (val.match(/[a-z]/g)) {
      lv++
    }
    if (val.match(/[0-9]/g)) {
      lv++
    }
    if (val.match(/([A-Z])/g)) {
      lv++
    }
    if (val.length < 8) {
      lv = 0
    }
    if (lv > 3) {
      lv = 3
    }
    return {
      lvTxt: lvTxts[lv],
      lvClass: lvClass[lv]
    }

  }

  downloadFile (fileName, blob) {
    console.log(blob)
    if (!(blob instanceof Blob)) {
      blob = new Blob([blob], {type: 'pplication/octet-stream'})
    }
    console.log(blob)
    let aLink = document.createElement('a')
    let evt = document.createEvent('MouseEvents')
    evt.initEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
    aLink.download = fileName
    aLink.href = URL.createObjectURL(blob)
    aLink.dispatchEvent(evt)
  }

  versionDataFile (obj) {
    let arr = []
    let key = obj.sys_conf_key
    let value = obj.sys_conf_value || ''
    let vs = value.split(',')
    return vs.map(item => {
        return {label: `${key}${item}`, value: `${key}${item}`}
      }) || []
  }
  getLocalTime(nS) {
    return new Date(parseInt(nS)).toLocaleString().replace(/:\d{1,2}$/,' ');
  }

  fetch (STORAGE_KEY) {
    return JSON.parse(window.localStorage.getItem(
        STORAGE_KEY) )
  }

  save (STORAGE_KEY, STORAGE_VAL) {
    // if (C.STORAGE_KEYS.indexOf(STORAGE_KEY) == -1) return false;   //注释HESB page212
    window.localStorage.setItem(STORAGE_KEY, JSON.stringify(STORAGE_VAL))
  }

  restoreSystem () {
    this.save('token', '')
    this.save('user_id', '')
    //this.setCookie('user_name', "", 30);
    // window.localStorage.clear()
  }

  // 是否可以删除提示
  deleteTips (name, ds) {
    let ms = ''
    if (ds == 1) {
      ms = '请先删除需要租户下面的策略'
    } else if (ds == 2) {
      // ms = '请先解除角色绑定'
    } else if (ds == 3) {
      ms = '请先删除租户下面的策略和解除角色绑定'
    } else if (ds == 4) {
      ms = '租户下关联任务正在运行,不能解绑该用户'
    }
    if (ms) {
      Message({
        message: `${name} : ${ms}`,
        type: 'warning'
      })
    }
  }

  validateChinese (rule, value, callback) {
    let re = /[\u4e00-\u9fa5]/
    if (re.test(value)) {
      callback(new Error('不能输入中文！'))
    }
    callback()
  }

  validateString (rule, value, callback) {

    if (/^[_a-zA-Z0-9]+$/.test(value)) {
      callback()
    } else {
      callback(new Error('只能输入英文字母和数字及_'))
    }
  }

  validateFileName (rule, value, callback) {
    if (/^[/._a-zA-Z0-9]+$/.test(value)) {
      callback()
    } else {
      callback(new Error('只能有英文字母和数字及_,不能有空格！'))
    }
  }

  validatePWS (rule, value, callback) {
    if (/^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,.\/]).{8,}$/.test(value)) {
      callback()
    } else {
      callback(new Error('密码必须8位以上包含字母，数字和特殊字符！'))
    }
  }

  validateTel (rule, value, callback) {
    let phoneN = /^1\d{10}$/;
    let telN = /^0\d{2,3}-?\d{7,8}$/;
    if (phoneN.test(value) || telN.test(value)) {
      callback()
    } else {
      callback(new Error('请输入正确的电话号码！'))
    }
  }
  rsaEncryption(data){
    let encrypt = new JSEncrypt();
    encrypt.setPublicKey(C.CMSZ_PUB);
    let encrypted = encrypt.encrypt(data);
    return encrypted
  }

  // cromExp = CronExpressionValidator
}

export default new fun()